package showgo.gui;

import java.awt.Toolkit;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class IntegerTextField extends JTextField {
    private static final long serialVersionUID = -2268029097438231803L;

    public IntegerTextField() {
	super();
	setDocument(new IntegerDocument());
    }

    public IntegerTextField(boolean allowNegativeNumber) {
	super();
	setDocument(new IntegerDocument(allowNegativeNumber));
    }

    public void setValue(int value) {
	setText(String.valueOf(value));
    }

    public int getValue() {
	int value = 0;
	if (!getText().isEmpty()) {
	    value = Integer.parseInt(getText());
	}
	return value;
    }
}

class IntegerDocument extends PlainDocument {
    /**
	 * 
	 */
    private static final long serialVersionUID = -6545036796702435856L;

    private boolean allowNegativeNumber = false;

    public IntegerDocument() {
    }

    public IntegerDocument(boolean allowNegativeNumber) {
	this.allowNegativeNumber = allowNegativeNumber;
    }

    public void insertString(int offset, String s, AttributeSet attributeSet)
	    throws BadLocationException {
	if (allowNegativeNumber && s.equals("-") && getLength() == 0) {
	    // wenn erstes Zeichen ein "-" dann nichts machen
	} else {
	    try {// sonst testen ob es eine Integer Zahle ist
		Integer.parseInt(s);
	    } catch (Exception ex) {
		Toolkit.getDefaultToolkit().beep(); // falls nicht Beep Ton
		return;
	    }
	}
	super.insertString(offset, s, attributeSet);
    }
}
